"""

"""

import json
import logging
from pathlib import Path
from typing import Dict, Any, List
from datetime import timedelta
from jinja2 import Environment, FileSystemLoader, select_autoescape

class OutputFormatter:
    """输出格式化器类"""

    def __init__(self, template_dir: str = "templates"):
        self.logger = logging.getLogger(__name__)
        # 配置 Jinja2 环境
        self.jinja_env = Environment(
            loader=FileSystemLoader(template_dir),
            autoescape=select_autoescape(['html', 'xml'])
        )
        self.jinja_env.filters['timestamp'] = self.format_time

    def format_time(self, seconds: float) -> str:
        """格式化时间为 HH:MM:SS,mmm 格式"""
        td = timedelta(seconds=float(seconds))
        hours, remainder = divmod(td.total_seconds(), 3600)
        minutes, seconds = divmod(remainder, 60)
        milliseconds = int((seconds % 1) * 1000)
        return f"{int(hours):02d}:{int(minutes):02d}:{int(seconds):02d},{milliseconds:03d}"

    def _render_template(self, template_name: str, context: Dict[str, Any]) -> str:
        """使用Jinja2模板渲染内容"""
        template = self.jinja_env.get_template(template_name)
        return template.render(context)

    def to_txt(self, result: Dict[str, Any], output_path: str) -> str:
        """输出为纯文本格式 (仅转录)"""
        try:
            content = result.get('transcript', {}).get('text', '')
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write(content)
            self.logger.info(f"TXT文件保存成功: {output_path}")
            return output_path
        except Exception as e:
            self.logger.error(f"保存TXT文件失败: {e}")
            raise

    def to_srt(self, result: Dict[str, Any], output_path: str) -> str:
        """输出为SRT字幕格式"""
        try:
            transcript_data = result.get('transcript', {})
            with open(output_path, 'w', encoding='utf-8') as f:
                if 'segments' not in transcript_data or not transcript_data['segments']:
                    f.write("1\n00:00:00,000 --> 00:00:01,000\n(无转录内容)\n\n")
                else:
                    for i, segment in enumerate(transcript_data['segments'], 1):
                        start_time = self.format_time(segment['start'])
                        end_time = self.format_time(segment['end'])
                        text = segment['text'].strip()
                        f.write(f"{i}\n{start_time} --> {end_time}\n{text}\n\n")
            self.logger.info(f"SRT文件保存成功: {output_path}")
            return output_path
        except Exception as e:
            self.logger.error(f"保存SRT文件失败: {e}")
            raise

    def to_vtt(self, result: Dict[str, Any], output_path: str) -> str:
        """输出为WebVTT字幕格式"""
        try:
            transcript_data = result.get('transcript', {})
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write("WEBVTT\n\n")
                if 'segments' not in transcript_data or not transcript_data['segments']:
                     f.write("00:00:00.000 --> 00:00:01.000\n(无转录内容)\n\n")
                else:
                    for segment in transcript_data['segments']:
                        start_time = self.format_time(segment['start']).replace(',', '.')
                        end_time = self.format_time(segment['end']).replace(',', '.')
                        text = segment['text'].strip()
                        f.write(f"{start_time} --> {end_time}\n{text}\n\n")
            self.logger.info(f"VTT文件保存成功: {output_path}")
            return output_path
        except Exception as e:
            self.logger.error(f"保存VTT文件失败: {e}")
            raise

    def to_json(self, result: Dict[str, Any], output_path: str) -> str:
        """输出为包含所有信息的JSON格式"""
        try:
            with open(output_path, 'w', encoding='utf-8') as f:
                json.dump(result, f, ensure_ascii=False, indent=2)
            self.logger.info(f"JSON文件保存成功: {output_path}")
            return output_path
        except Exception as e:
            self.logger.error(f"保存JSON文件失败: {e}")
            raise
    
    def to_md(self, result: Dict[str, Any], output_path: str) -> str:
        """输出为Markdown报告"""
        try:
            content = self._render_template('summary.md.jinja2', result)
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write(content)
            self.logger.info(f"Markdown文件保存成功: {output_path}")
            return output_path
        except Exception as e:
            self.logger.error(f"保存Markdown文件失败: {e}")
            raise

    def to_html(self, result: Dict[str, Any], output_path: str) -> str:
        """输出为HTML报告"""
        try:
            content = self._render_template('summary.html.jinja2', result)
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write(content)
            self.logger.info(f"HTML文件保存成功: {output_path}")
            return output_path
        except Exception as e:
            self.logger.error(f"保存HTML文件失败: {e}")
            raise

    def to_mm(self, result: Dict[str, Any], output_path: str) -> str:
        """输出为FreeMind思维导图格式"""
        try:
            content = self._render_template('summary.mm.jinja2', result)
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write(content)
            self.logger.info(f"思维导图(.mm)文件保存成功: {output_path}")
            return output_path
        except Exception as e:
            self.logger.error(f"保存思维导图文件失败: {e}")
            raise

    def save_result(self, result: Dict[str, Any], output_path: str,
                   format_type: str = 'md') -> str:
        """根据格式类型保存结果"""
        Path(output_path).parent.mkdir(parents=True, exist_ok=True)

        format_methods = {
            'txt': self.to_txt,
            'srt': self.to_srt,
            'vtt': self.to_vtt,
            'json': self.to_json,
            'md': self.to_md,
            'html': self.to_html,
            'mm': self.to_mm,
        }

        if format_type not in format_methods:
            raise ValueError(f"不支持的输出格式: {format_type}")

        return format_methods[format_type](result, output_path)

    def save_multiple_formats(self, result: Dict[str, Any], base_path: str,
                            formats: List[str] = None) -> Dict[str, str]:
        """保存多种格式的输出"""
        if formats is None:
            formats = ['md', 'srt']

        saved_files = {}
        base_name = Path(base_path).stem
        base_dir = Path(base_path).parent

        for fmt in formats:
            try:
                output_path = base_dir / f"{base_name}.{fmt}"
                saved_path = self.save_result(result, str(output_path), fmt)
                saved_files[fmt] = saved_path
            except Exception as e:
                self.logger.error(f" 保存 {fmt} 格式失败: {e}")
                saved_files[fmt] = None

        return saved_files